<!-- 品牌制造商 -->
<template>
  <div class="app-container">
    <!-- 搜索 -->
    <el-form :inline="true" :model="formInline" class="demo-form-inline">
      <el-form-item>
        <el-input v-model="formInline.id" placeholder="请输入品牌商ID" clearable></el-input>
      </el-form-item>
      <el-form-item>
        <el-input v-model="formInline.name" placeholder="请输入品牌商名称" clearable></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="checkForm" icon="el-icon-search" size="mini">查找</el-button>
        <el-button type="primary" @click="addForm" icon="el-icon-edit" size="mini">添加</el-button>
        <el-button type="primary" @click="downExcel" icon="el-icon-download" size="mini">导出</el-button>
      </el-form-item>
    </el-form>
    <!-- 列表 -->
    <el-table :data="tableData" border style="width: 100%">
      <el-table-column prop="id" label="品牌商ID" min-width="10%" align="center">
      </el-table-column>
      <el-table-column prop="name" label="品牌商名称" min-width="10%" align="center">
      </el-table-column>
      <el-table-column label="品牌商图片" min-width="10%" align="center">
        <template slot-scope="scope">
          <el-image :src="scope.row.picUrl" alt="品牌商图片" :preview-src-list="srcList" style="width: 40px;height: 40px;">
          </el-image>
        </template>
      </el-table-column>
      <el-table-column prop="desc" label="介绍" show-overflow-tooltip min-width="50%" align="center">
      </el-table-column>
      <el-table-column prop="floorPrice" label="底价" min-width="10%" align="center">
      </el-table-column>
      <el-table-column label="操作" min-width="10%" align="center">
        <template slot-scope="scope">
          <div class="btn">
            <el-button size="mini" @click="handleEdit(scope.$index, scope.row)" type="primary">编辑</el-button>
            <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row.id)">删除</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <!-- 按钮 -->
    <div class="block">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
        :page-sizes="[10, 20, 30, 40, 50, 100]" :page-size="size" layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </div>
    <!-- 模态框 -->
    <el-dialog title="创建" :visible.sync="dialogFormVisible">
      <el-form :model="form" :rules="rules" ref="form">
        <el-form-item label="品牌制造商" :label-width="formLabelWidth" prop="name">
          <el-input v-model="form.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="介绍" :label-width="formLabelWidth">
          <el-input v-model="form.desc" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="品牌商图片" :label-width="formLabelWidth">
          <el-upload class="avatar-uploader" :action="iconUrl" :show-file-list="false"
            :on-success="handleAvatarSuccess">
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="底价" :label-width="formLabelWidth">
          <el-input v-model="form.floorPrice" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <!-- 新增 -->
        <el-button type="primary" @click="confirmFun" v-show="show">确 定</el-button>
        <!-- 编辑 -->
        <el-button type="primary" @click="editFun" v-show="!show">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getList, addList, editList, delList } from "@/api/scgl/brand";
import * as XLSX from "xlsx";
export default {
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: "success",
        draft: "gray",
        deleted: "danger",
      };
      return statusMap[status];
    },
  },
  data() {
    return {
      listLoading: true,
      // 表格数据
      tableData: [],
      queryParams: {}, //地址拼接的参数
      picUrl: '',
      srcList: [
        'http://admin.bsmall.byesame.com/wx/storage/fetch/g3ybo187ccun71o2tg03.jpg'
      ],
      // 分页
      currentPage: 1,
      size: 20,
      total: 0,
      // 查询条件
      formInline: {},
      id: '',
      name: '',
      // 模态框
      dialogFormVisible: false,
      form: {},
      formLabelWidth: '120px',
      rules: {
        name: [
          { required: true, message: '品牌商名称不能为空', trigger: 'blur' }
        ],
      },
      // 上传头像
      imageUrl: '',
      iconUrl: "",//默认图片
      // 导出图片
      columns: [
        { title: "品牌商ID", key: "id" },
        { title: "车品牌商名称", key: "name" },
        { title: "品牌商图片", key: "picUrl" },
        { title: "介绍", key: "desc" },
        { title: "底价", key: "floorPrice" },
      ],
      show: true,
    };
  },
  created() {
    this.getParams();
    this.fetchData();
    this.iconUrl = "/api/admin/storage/create";
  },
  methods: {
    // 获取拼接参数
    getParams() {
      this.queryParams = {
        page: this.currentPage,
        limit: this.size,
        sort: 'add_time',
        order: 'desc',
        id: this.id,
        name: this.name,
      };
    },
    fetchData() {
      this.listLoading = true;
      getList(this.queryParams).then((response) => {
        console.log(response);
        this.tableData = response.data.list
        this.total = response.data.total
        this.srcList = response.data.list.map(item => item.picUrl)
        this.listLoading = false;
      });
    },

    // 查找
    checkForm() {
      this.currentPage = 1
      this.id = this.formInline.id
      this.name = this.formInline.name
      this.getParams()
      this.fetchData()
    },
    // 添加
    addForm() {
      this.dialogFormVisible = true
      this.form = {}
      this.show = true
      this.imageUrl = ''
    },
    // 上传图片
    handleAvatarSuccess(res, file) {
      console.log(res.data.url)
      this.form.picUrl = res.data.url //给接口传递数据，还需要给form赋值
      this.imageUrl = URL.createObjectURL(file.raw);
    },
    // 添加确认
    confirmFun() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          addList(this.form).then((response) => {
            console.log(response);
            this.fetchData();
            this.dialogFormVisible = false
            this.$notify({
              title: "成功",
              message: "创建成功",
              type: "success",
            });
          }).catch((error) => {
            console.error("Error during submission:", error);
            this.$notify({
              title: "失败",
              message: response.errmsg,
              type: "error",
            });
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 导出
    downExcel() {
      this.$confirm("确定导出excel文件?", "提示", {
        type: "warning",
      }).then(() => {
        this.exportToExcel();
      }).catch(() => {
        this.$message({
          type: "info",
          message: "已取消导出Excel文件",
          duration: 2000,
        });
      });
    },
    exportToExcel() {
      const data = this.tableData.map(row => {
        const newObj = {};
        this.columns.forEach(col => {
          newObj[col.title] = row[col.key];
        });
        return newObj;
      });
      // 创建工作表
      const ws = XLSX.utils.json_to_sheet(data);
      // 创建工作簿并添加工作表
      const wb = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(wb, ws, "Sheet1");
      // 导出Excel文件
      XLSX.writeFile(wb, '品牌商信息.xlsx');
    },

    // 编辑
    handleEdit(index, row) {
      console.log(index, row);
      this.show = false
      this.dialogFormVisible = true
      this.form = { ...row }
      this.imageUrl = row.picUrl
    },
    // 编辑确认
    editFun() {
      editList(this.form).then((response) => {
        console.log(response);
        this.fetchData();
        this.dialogFormVisible = false
        this.$notify({
          title: "成功",
          message: "更新成功",
          type: "success",
        });
      }).catch((error) => {
        console.error("Error during submission:", error);
        this.$notify({
          title: "失败",
          message: "参数不对",
          type: "success",
        });
      });
    },
    // 删除
    handleDelete(index, id) {
      console.log(index, id);
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delList({ id: id }).then((response) => {
          console.log(response);
          this.fetchData();
          this.dialogFormVisible = false
          this.$notify({
            title: "成功",
            message: "删除成功",
            type: "success",
          });
        }).catch((error) => {
          console.error("Error during submission:", error);
          this.$notify({
            title: "失败",
            message: "参数不对",
            type: "success",
          });
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },

    // 分页
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.size = val
      this.getParams()
      this.fetchData();
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.currentPage = val
      this.getParams()
      this.fetchData();
    },

  },
};
</script>
<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

/* 按钮 */
.btn {
  display: flex;
  justify-content: center;
}
</style>
